package com.coder4j.starter.generator.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.util.List;
import java.util.Map;


public class GeneratorUtil {

    static final String tableListSql = "SELECT table_name,table_comment " +
            "FROM information_schema.tables WHERE table_schema = '%s'";


    public static void main(String[] args) {
//        JdbcTemplate jdbcTemplate = initJdbcTemplate();
//
//
//        String tableListSql = "SELECT table_name,table_comment FROM information_schema.tables WHERE table_schema = 'keller_note'";
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(tableListSql);
//
//        System.out.println(JSON.toJSONString(list));
        TableConnection connection = new TableConnection();
        connection.setDatabase("keller_note");
        List<Table> tableList = getTableList(connection);
    }

    public static List<Table> getTableList(TableConnection connection){
        JdbcTemplate jdbcTemplate = initJdbcTemplate();
        String sql = String.format(tableListSql,connection.getDatabase());
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);

        List<Table> list = JSON.parseArray(JSON.toJSONString(result), Table.class);
        System.out.println(JSON.toJSONString(list));
        return list;
    }

    public static JdbcTemplate initJdbcTemplate(TableConnection connection) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(connection.getUrlStr() + "/" + connection.getDatabase());
        dataSource.setUsername(connection.getUsername());
        dataSource.setPassword(connection.getPassword());
        return new JdbcTemplate(dataSource);
    }




    public static JdbcTemplate initJdbcTemplate() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/keller_note");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return new JdbcTemplate(dataSource);
    }




}
